package com.zhen.aikan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhen.aikan.entity.Favourite;
import com.zhen.aikan.entity.VodDetail;
import com.zhen.aikan.mapper.FavouriteMapper;
import com.zhen.aikan.service.IFavouriteService;
import com.zhen.aikan.service.IVodDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author LiJiaZhen
 * @date 2023/9/25 10:33
 */
@Service
public class FavouriteServiceImpl extends ServiceImpl<FavouriteMapper, Favourite> implements IFavouriteService {
    @Autowired
    private IVodDetailService vodDetailService;

    @Override
    public boolean addFavourite(String userId, String vodId) {
        if (!StringUtils.hasText(userId) && !StringUtils.hasText(vodId)) {
            return false;
        }
        Favourite favourite = new Favourite();
        favourite.setUserId(userId);
        favourite.setVodId(Long.parseLong(vodId));
        favourite.setFavouriteTime(LocalDateTime.now());
        return save(favourite);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deleteFavourite(String userId, String vodId) {
        if (!StringUtils.hasText(userId) && !StringUtils.hasText(vodId)) {
            return false;
        }
        int delete = baseMapper.delete(new QueryWrapper<Favourite>().eq("user_id", userId).eq("vod_id", vodId));
        return delete > 0;
    }

    @Override
    public List<VodDetail> getFavouriteByUserId(String userId) {
        if (!StringUtils.hasText(userId)) {
            return null;
        }
        List<Favourite> favourites = baseMapper.selectList(new QueryWrapper<Favourite>().eq("user_id", userId));
        return favourites.stream().map(item -> vodDetailService.getVodDetailById(item.getVodId())).collect(Collectors.toList());
    }

    @Override
    public boolean isFavourite(String userId, String vodId) {
        if (!StringUtils.hasText(userId) && !StringUtils.hasText(vodId)) {
            return false;
        }
        Long count = baseMapper.selectCount(new QueryWrapper<Favourite>().eq("user_id", userId).eq("vod_id", vodId));
        return count > 0;
    }
}
